package com.cloud.api.log.controller;

import com.alibaba.fastjson.JSONObject;
import com.cloud.api.log.entity.CloudApiLogEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.Message;

import java.io.UnsupportedEncodingException;
import java.util.Date;

@EnableBinding(value = {Sink.class})
public class ReceiveService {

    /**
     * spring cloud stream里面通过 Sink 接收消息
     */


    @Autowired
    private MongoTemplate mongoTemplate;


    @StreamListener(value = Sink.INPUT)
    public void listener(Message<byte[]> message) throws UnsupportedEncodingException {
        System.out.println("headers：" + message.getHeaders());
        byte[] payload = message.getPayload();
        String s = new String(payload, "utf-8");
        CloudApiLogEntity cloudApiLog = JSONObject.parseObject(s, CloudApiLogEntity.class);
        System.out.println("接收到的消息：" + new String(payload, "utf-8"));

        cloudApiLog.setCreateTime(new Date());
        CloudApiLogEntity insert = mongoTemplate.insert(cloudApiLog);
        System.out.println("...."+insert);
        System.out.println(cloudApiLog);
    }
}